package com.yc.jpyy.base.service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public abstract class BaseService {
	/**
	 * 分页
	 * @param paramsMap
	 */
	protected static void checkPageParamsMap(Map<String, Object> paramsMap){
		String currentPage_ = paramsMap.get("PageNum") == null ? "1" : String.valueOf(paramsMap.get("PageNum"));
		currentPage_ = currentPage_.trim().equals("") ? "1" : currentPage_;
		int currentPage = Integer.parseInt(currentPage_);
		String pageSize_ = paramsMap.get("PageSize") == null ? "10" : String.valueOf(paramsMap.get("PageSize"));
		pageSize_ = pageSize_.trim().equals("") ? "10" : pageSize_;
		int pageSize = Integer.parseInt(pageSize_);
		
		int begin = (currentPage-1) * pageSize;
		int endNum = begin + pageSize;
		
		paramsMap.put("beginNum", (currentPage-1) * pageSize + 1);
		paramsMap.put("endNum", endNum);
	}
	
	/**
	 * sqlserver分页:
	 * @param paramsMap
	 */
	protected static void checkParamsMapForPage(Map<String, Object> paramsMap){
		String currentPage_ = paramsMap.get("PageNum") == null ? "1" : String.valueOf(paramsMap.get("PageNum"));
		currentPage_ = currentPage_.trim().equals("") ? "1" : currentPage_;
		int currentPage = Integer.parseInt(currentPage_);
		String pageSize_ = paramsMap.get("PageSize") == null ? "10" : String.valueOf(paramsMap.get("PageSize"));
		pageSize_ = pageSize_.trim().equals("") ? "10" : pageSize_;
		int pageSize = Integer.parseInt(pageSize_);	
		int topNum = pageSize;
		paramsMap.put("beginNum", (currentPage-1) * pageSize);
		paramsMap.put("topNum", topNum);
	}

	protected static List<String> getMonthBetween(LocalDate minDate, LocalDate maxDate) throws Exception {
        List<String> result = new ArrayList<String>();
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM");
        while(minDate.isBefore(maxDate)) {
            result.add(minDate.format(sdf));
            minDate = minDate.plusMonths(1);
            //当当前日期为1号的时候，能获取到当前月
            if(minDate.isEqual(maxDate)){
                result.add(maxDate.format(sdf));
            }
        }
        return result;
    }
	
	protected static List<String> getDayBetween(LocalDate minDate, LocalDate maxDate)throws Exception {
        List<String> result = new ArrayList<String>();
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        while(minDate.isBefore(maxDate)) {
            result.add(minDate.format(sdf));
            minDate = minDate.plusDays(1);
            //当当前日期为1号的时候，能获取到当前月
            if(minDate.isEqual(maxDate)){
                result.add(maxDate.format(sdf));
            }
        }
        return result;
    }
	
	protected static List<Map<String,Object>> getResultList(List<String> monthlist,List<Map<String,Object>> mapList,String driverId){
		List<Map<String,Object>> mapListNew = new ArrayList<Map<String,Object>>();
		monthlist.stream().forEach(month -> {
			List<Map<String,Object>> newList = mapList.stream().filter(map -> map.get("times").toString()
					.equals(month)).collect(Collectors.toList());
			if(newList.size() > 0){
				mapListNew.add(newList.get(0));
			}else{
				Map<String,Object> newMap = new HashMap<>();
				newMap.put("DriveSchoolId", driverId);
				newMap.put("years", month.split("-")[0]);
				newMap.put("months", Integer.parseInt(month.split("-")[1])<10?month.substring(6,7):month.split("-")[1]);
				newMap.put("monthTotal", 0);
				newMap.put("times", month);
				mapListNew.add(newMap);
			}
		});
		return mapListNew;	
	}
	
	protected static List<Map<String,Object>> getDayResultList(List<String> daylist,List<Map<String,Object>> mapList,String driverId){
		List<Map<String,Object>> mapListNew = new ArrayList<Map<String,Object>>();
		daylist.stream().forEach(day -> {
			List<Map<String,Object>> newList = mapList.stream().filter(map -> map.get("times").toString()
					.equals(day)).collect(Collectors.toList());
			if(newList.size() > 0){
				mapListNew.add(newList.get(0));
			}else{
				Map<String,Object> newMap = new HashMap<>();
				newMap.put("years", day.split("-")[0]);
				newMap.put("months", Integer.parseInt(day.split("-")[1])<10?day.substring(6,7):day.split("-")[1]);
				newMap.put("days", Integer.parseInt(day.split("-")[2])<10?day.substring(8,9):day.split("-")[2]);
				newMap.put("EffectiveRate", 0);
				newMap.put("times", day);
				mapListNew.add(newMap);
			}
		});
		return mapListNew;	
	}
	
	public static String HttpPostWithJson(String url, String json) {
		String returnValue = "这是默认返回值，接口调用失败";
		CloseableHttpClient httpClient = HttpClients.createDefault();
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		try{
			//第一步：创建HttpClient对象
		    //httpClient = HttpClients.createDefault();	
		 	//第二步：创建httpPost对象
	        HttpPost httpPost = new HttpPost(url); 
	        //第三步：给httpPost设置JSON格式的参数
	        StringEntity requestEntity = new StringEntity(json,"utf-8");
	        requestEntity.setContentEncoding("UTF-8");    	        
	        httpPost.setHeader("Content-type", "application/json");
	        httpPost.setEntity(requestEntity);
	        //第四步：发送HttpPost请求，获取返回值
	       returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时，必须用此方法 
		}catch(Exception e){
			 e.printStackTrace();
		}
	    finally {
	       try {
			httpClient.close();
		   } catch (IOException e){
			e.printStackTrace();
		  }
	    }
		 //第五步：处理返回值
	     return returnValue;
	}
	
	
	public static String HttpPostWithUrlEncoder(String url,List<NameValuePair> params) {
		String returnValue = "这是默认返回值，接口调用失败";
		CloseableHttpClient httpClient = HttpClients.createDefault();
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		try{
			//第一步：创建HttpClient对象
		    httpClient = HttpClients.createDefault();	
		 	//第二步：创建httpPost对象
	        HttpPost httpPost = new HttpPost(url); 
	        //第三步：给httpPost设置JSON格式的参数
	        StringEntity requestEntity = new UrlEncodedFormEntity(params,"UTF-8");        
	        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
	        httpPost.setEntity(requestEntity);
	        //第四步：发送HttpPost请求，获取返回值
	       returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时，必须用此方法 
		}catch(Exception e){
			 e.printStackTrace();
		}
	    finally {
	       try {
			httpClient.close();
		   } catch (IOException e){
			e.printStackTrace();
		  }
	    }
		 //第五步：处理返回值
	     return returnValue;
	}


}
